package com.cos.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.cos.constant.DataSource;
import com.cos.constant.LoginSuccess;
import com.cos.utils.OidUtils;
import com.cos.vo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DynamicDataSource implements HandlerInterceptor {
    @Autowired
    private OidUtils oidUtils;
    public  Integer threadLocal(){
        return threadLocal.get();
    }
    private ThreadLocal<Integer> threadLocal =new ThreadLocal();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        Customer customer = (Customer) request.getSession().getAttribute(LoginSuccess.LOGIN_SUCCESS);
        if (customer != null) {
            //计算数据库的编号
            String uid = oidUtils.lastUid(customer.getId());
            String orderId = oidUtils.createOrderId(Integer.parseInt(uid));
            Integer dataIndex=Integer.parseInt(uid)% DataSource.TABLEINDEX+1;
            //表的编号
            Integer tableIndex=Integer.parseInt(uid)/DataSource.DATAINDEX%DataSource.TABLEINDEX+1;
            //创建数据源key
            String s = DataSource.ORDER_DB_TABLE + dataIndex;
            //设置数据源
            DynamicDataSourceContextHolder.push(s);
            System.out.println("数据库的编号是:"+dataIndex);
            System.out.println("表的编号是:"+tableIndex);
            //将表的编号传到service中  通过threadLocal将值通过当前线程一直传递下去
            threadLocal.set(tableIndex);
        }else {
            response.sendRedirect("http://localhost/auth/login.html");
        }
        //放行
        return true;
    }
}
